#!/bin/bash

# 充电宝租赁系统停止脚本
# 作者：AI Assistant
# 版本：1.0.0

echo "=================================="
echo "充电宝租赁系统停止脚本"
echo "=================================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 基础目录
BASE_DIR=$(pwd)
LOG_DIR="$BASE_DIR/logs"

# 服务列表
SERVICES=(
    "powerbank-user-api"
    "powerbank-admin-api"
    "powerbank-device-service"
)

# 停止服务函数
stop_service() {
    local service_name=$1
    local pid_file="$LOG_DIR/$service_name.pid"
    
    echo -n "停止 $service_name: "
    
    if [ -f "$pid_file" ]; then
        local pid=$(cat "$pid_file")
        
        if ps -p $pid > /dev/null 2>&1; then
            kill $pid
            sleep 3
            
            # 检查是否成功停止
            if ps -p $pid > /dev/null 2>&1; then
                echo -e "${YELLOW}强制停止...${NC}"
                kill -9 $pid
                sleep 1
            fi
            
            if ps -p $pid > /dev/null 2>&1; then
                echo -e "${RED}停止失败${NC}"
                return 1
            else
                echo -e "${GREEN}已停止${NC}"
                rm -f "$pid_file"
                return 0
            fi
        else
            echo -e "${YELLOW}进程不存在${NC}"
            rm -f "$pid_file"
            return 0
        fi
    else
        echo -e "${YELLOW}PID文件不存在${NC}"
        return 0
    fi
}

# 停止所有服务
echo "正在停止所有微服务..."
echo ""

for service_name in "${SERVICES[@]}"; do
    stop_service "$service_name"
done

echo ""

# 清理Java进程（备用方案）
echo "检查残留的Java进程..."

java_pids=$(ps aux | grep "spring-boot:run" | grep -v grep | awk '{print $2}')

if [ -n "$java_pids" ]; then
    echo "发现残留的Spring Boot进程，正在清理..."
    for pid in $java_pids; do
        echo "停止进程 $pid"
        kill $pid
    done
    sleep 3
    
    # 再次检查
    java_pids=$(ps aux | grep "spring-boot:run" | grep -v grep | awk '{print $2}')
    if [ -n "$java_pids" ]; then
        echo "强制停止残留进程..."
        for pid in $java_pids; do
            kill -9 $pid
        done
    fi
fi

echo ""

# 清理端口占用
echo "检查端口占用情况..."

PORTS=(8081 8082 8083)

for port in "${PORTS[@]}"; do
    if command -v lsof >/dev/null 2>&1; then
        pid=$(lsof -ti:$port)
        if [ -n "$pid" ]; then
            echo "端口 $port 仍被进程 $pid 占用，正在释放..."
            kill -9 $pid
        fi
    elif command -v netstat >/dev/null 2>&1; then
        netstat_result=$(netstat -tulpn 2>/dev/null | grep ":$port ")
        if [ -n "$netstat_result" ]; then
            echo "端口 $port 仍被占用"
        fi
    fi
done

echo ""

# 清理日志（可选）
read -p "是否清理日志文件？(y/N): " clean_logs
if [[ $clean_logs =~ ^[Yy]$ ]]; then
    if [ -d "$LOG_DIR" ]; then
        rm -rf "$LOG_DIR"/*.log
        rm -rf "$LOG_DIR"/*.pid
        echo -e "${GREEN}日志文件已清理${NC}"
    fi
fi

echo ""
echo -e "${GREEN}所有服务已停止${NC}"
echo "=================================="

exit 0